package com.example.wifijailbreak.conn;

import cn.hutool.core.io.FileUtil;
import com.example.wifijailbreak.config.WifiProfile;
import com.example.wifijailbreak.thread.GenThread;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class WifiProfileGen extends WifiCollisionProcessing<String> {

    private Executor proFileThreadPool = newFixedThreadPool(100);

    @Override
    public void handler(String ssid) {
        try {
            File pwdFileDir = new File(WifiProfile.DICTIONARY_PATH);
            File[] pwdFiles = pwdFileDir.listFiles();
            for (File pwdFile : pwdFiles) {
                Path path = Paths.get(pwdFile.getAbsolutePath());
                BufferedReader reader = Files.newBufferedReader(path);
                long count = Files.lines(path).count();
                CountDownLatch latch = new CountDownLatch(Integer.parseInt(String.valueOf(count)));
                while (reader.ready()) {
                    String password = reader.readLine();
                    String profileName = RandomStringUtils.randomNumeric(20) + ".xml";
                    GenThread profileGenerator = new GenThread(ssid, password, profileName, latch);
                    proFileThreadPool.execute(profileGenerator);
                }
                latch.await();
                recordGenFile(pwdFile);
                wifiCollisionProcessing.handler(ssid);
            }
        } catch (Exception e) {
            System.out.println("wifi profile文件生成异常:" + e.getMessage());
        }
    }

    private void recordGenFile(File pwdFile) {
        new Thread(() -> {
            String record = "D:\\record.txt";
            FileUtil.newFile(record);
            FileUtil.appendString(pwdFile.getName() + "\r\n", record, StandardCharsets.UTF_8);
            FileUtil.del(pwdFile);
        }).start();
    }
}
